/**       
 * @{#} ProcessPool.java Create on 2012-3-26 下午9:09:25       
 *       
 * Copyright (c) 2012 by able.       
 */
package __javable.core.util;

import java.util.LinkedList;
import java.util.List;

/**
 * 
 * 
 * @history <PRE>
 * --------------------------------------------------------- 
 * VERSION       DATE            BY       CHANGE/COMMENT 
 * --------------------------------------------------------- 
 * 1.0           2012-3-26      able         create 
 * ---------------------------------------------------------
 * </PRE>
 * 
 *          question:
 * 
 *          1、线程被占用无法释放怎么办？
 * 
 */
public abstract class ProcessPool<T> implements Runnable {

	protected T connection;
	protected static List<Object> pool = new LinkedList<Object>();

	public ProcessPool() {
	}

	public ProcessPool(int threadCount) {
		final ProcessPool<T> e = this;
		for (int i = 0; i < threadCount; i++) {
			new Thread(new ProcessPool<T>() {
				@Override
				public void Process(T obj) {
					e.Process(obj);
				}
			}, "thread-" + i).start();
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public void run() {
		while (true) {
			synchronized (pool) {
				while (pool.isEmpty()) {
					try {
						pool.wait();
					} catch (InterruptedException e) {
						return;
					}
				}
				connection = (T) pool.remove(0);

				System.out.println(Thread.currentThread().getName()
						+ " pick up a connection.");
			}
			Process(connection);
		}
	}

	public static void push(Object obj) {
		synchronized (pool) {
			pool.add(pool.size(), obj);
			pool.notifyAll();
		}
	}

	public abstract void Process(T obj);
}